﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using QuTouTiaoAssist.Entity;
using QuTouTiaoAssist.Util;

namespace QuTouTiaoAssist
{
    public partial class FrmReg : FrmOkCancelBase
    {
        private bool m_isCracking = false;
        private string mobile;
        private string pwd;
        private string inviteCode;
        private string smsCaptcha;
        private string smsCaptchaCracked;
        private int usedNum = 0;
        private bool stopNeeded = false;

        /// <summary>
        /// 构造函数
        /// </summary>
        public FrmReg()
        {
            InitializeComponent();
            base.EnableCancelButton(); 
            ValidateRules.Add(this.txtMobile, new ControlTextValidate(this.txtMobile, OtherUtil.IsMobile, "请输入11位有效的手机号！", true));
            ValidateRules.Add(this.txtSmsCaptcha, new ControlTextValidate(this.txtSmsCaptcha, OtherUtil.IsNullOrWhitespace, "短信验证码不能为空！", true, true));
            ValidateRules.Add(this.txtPwd, new ControlTextValidate(this.txtPwd, string.IsNullOrEmpty, "密码不能为空！", false, true));
            this.txtPwd.Text = ConfigUtil.GetDefaultPassword();
            this.txtInviteCode.Text = ConfigUtil.GetDefaultInviteCode();
        }

        /// <summary>
        /// 从联通官网获取随机手机号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRandomMobile_Click(object sender, EventArgs e)
        {
            this.txtMobile.Clear();
            try
            {
                var mobiles = ChinaUnicomUtil.GetMobiles();
                Random r = new Random();
                var mobileIndex = r.Next(0, mobiles.Count - 1);
                this.txtMobile.Text = mobiles[mobileIndex];
            }
            catch (Exception ex)
            {
                MsgBox.ShowInfo("获取失败，" + ex.Message);
            }
        }

        /// <summary>
        /// 获取图片验证码，并发送短信验证码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGetVerifyCode_Click(object sender, EventArgs e)
        {
            if (m_isCracking)
                return;

            this.errorProvider1.Clear();
            string mobile = this.txtMobile.Text.Trim();
            if (!base.CheckValidateRule(this.txtMobile))
                return;

            var frm = new FrmImageVerifyCode();
            frm.RefreshImage += (o, args) =>
            {
                args.Img = QttHelper.GetImgCaptcha(mobile);
            };
            frm.ConfirmVerifyCode += () =>
            {
                var result = QttHelper.GetSmsCaptcha(mobile, frm.VerifyCode);
                if (result.Code == 0)
                {
                    //MsgBox.ShowInfo("验证码已经发送到您的手机！");
                    return true;
                }
                else
                {
                    MsgBox.ShowInfo("错误，" + result.Message);
                    return false;
                }
            };
            frm.ShowDialog();
        }

        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnReg_Click(object sender, EventArgs e)
        {
            if (m_isCracking)
                return;

            this.errorProvider1.Clear();
            mobile = this.txtMobile.Text.Trim();
            smsCaptcha = this.txtSmsCaptcha.Text.Trim();
            pwd = this.txtPwd.Text;
            inviteCode = this.txtInviteCode.Text.Trim();

            foreach (var rule in ValidateRules.Values)
            {
                if (!rule.IsValid())
                {
                    this.errorProvider1.SetError(rule.ValidateControl,rule.ErrorMsg);
                    return;
                }
            }

            var result = QttHelper.Register(mobile, pwd, smsCaptcha, inviteCode);
            MsgBox.ShowInfo(result);
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            this.txtPwd.PasswordChar = this.checkBox1.Checked ? '\0' : '*';
        }

        /// <summary>
        /// “选择邀请码”按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelectInviteCode_Click(object sender, EventArgs e)
        {
            ContextMenuStrip cms = new ContextMenuStrip();
            var users = ConfigUtil.GetUserInfos(); // 获取所有用户
            if (users.Count < 1)
            {
                cms.Items.Add("无", null, null);
            }
            else
            {
                foreach (var user in users)
                {
                    cms.Items.Add(user.NickName, null, (o, args) =>
                    {
                        this.txtInviteCode.Clear();
                        var u = (o as ToolStripItem).Tag as QttMemberInfoLite;
                        new Thread(() =>
                        {
                            try
                            {
                                var result = QttHelper.GetMemberInfo(u.Token);
                                if (result.Code != 0)
                                {
                                    throw new Exception(result.Message);
                                }
                                base.SetControlText(this.txtInviteCode, result.Data.InviteCode);
                            }
                            catch (Exception ex)
                            {
                                MsgBox.ShowInfo("获取失败，" + ex.Message);
                            }
                        }){IsBackground = true}.Start();
                    }).Tag = user;
                }
            }
            var point = this.btnSelectInviteCode.Location;
            point.Y += this.btnSelectInviteCode.Height;
            cms.Show(this, point);
        }
    }
}
